/*
 * MIT License
 *
 * Copyright (c) 2020 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.openapi.item;

import cn.seaboot.commons.core.CommonUtils;
import cn.seaboot.openapi.Environment;
import cn.seaboot.openapi.PostmanBuilder;
import cn.seaboot.openapi.base.ControllerInfo;
import cn.seaboot.openapi.base.FormType;
import cn.seaboot.openapi.base.MethodInfo;
import cn.seaboot.openapi.request.*;
import cn.seaboot.openapi.response.DefaultResponseAnalyzer;
import cn.seaboot.openapi.response.ResponseAnalyzer;
import cn.seaboot.postman.request.Body;
import cn.seaboot.postman.request.Query;
import cn.seaboot.postman.request.Request;
import cn.seaboot.postman.request.Url;
import cn.seaboot.postman.response.Response;
import cn.seaboot.postman.root.Item;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 扫描一个 Controller 中所包含的所有 API
 * <p>
 * 负责将其它扫描器的数据组装起来，形成 {@link Item}
 *
 * @author Mr.css
 * @version 2022-02-10 15:23
 */
public class DefaultItemAnalyzer implements ItemAnalyzer {
    private final Logger logger = LoggerFactory.getLogger(DefaultItemAnalyzer.class);

    private final PostmanBuilder postmanBuilder;

    public DefaultItemAnalyzer(PostmanBuilder postmanBuilder) {
        this.postmanBuilder = postmanBuilder;
    }

    /**
     * 表单参数扫描
     */
    private QueryAnalyzer queryAnalyzer = new DefaultQueryAnalyzer();

    /**
     * 数据响应扫描
     */
    private ResponseAnalyzer responseAnalyzer = new DefaultResponseAnalyzer();

    /**
     * 查询参数转换成 FormData
     */
    private QueryToFormDataConverter queryToFormDataConverter = new DefaultQueryToFormDataConverter();
    /**
     * 查询参数转换成 RequestBody
     */
    private QueryToRequestBodyConverter queryToRequestBodyConverter = new DefaultQueryToRequestBodyConverter();

    /**
     * {@inheritDoc}
     */
    @NotNull
    @Override
    public List<Item> analyze(ControllerInfo controllerInfo) {
        // search all api form controller's method
        List<Item> controllerApi = new ArrayList<>();
        for (MethodInfo method : controllerInfo.getMethodInfos()) {
            if (logger.isDebugEnabled()) {
                logger.debug("start analyze：" + controllerInfo.getTarget() + "." + method.getMethod().getName());
            }
            this.analyzeMethod(controllerInfo, method, controllerApi);
        }

        // 将一个 controller 所有的接口，封装成一个 item 对象
        List<Item> ret = new ArrayList<>();
        if (CommonUtils.isNotEmpty(controllerApi)) {
            Item groupItem = new Item();
            groupItem.setName(controllerInfo.getControllerDescription());
            groupItem.setItem(controllerApi.toArray(new Item[]{}));
            ret.add(groupItem);
        }
        return ret;
    }

    /**
     * 扫描一个 Controller 的所有方法
     * <p>
     * 这个函数看起来很长，为了避免重复扫描，已经做了适当优化，不需要继续拆分。
     * <p>
     * Get a api-group form a method, and add result into controllerApi.
     *
     * @param controllerInfo -
     * @param methodInfo     -
     * @param controllerApi  api of a controller
     */
    private void analyzeMethod(ControllerInfo controllerInfo, MethodInfo methodInfo, List<Item> controllerApi) {
        // 获取方法上的所有请求参数
        List<Query> queryList = queryAnalyzer.analyze(methodInfo);

        // 请求方式以及接口描述
        String requestMethod = methodInfo.getRequestMethod();
        String requestDescription = methodInfo.getMethodDescription();

        // 获取表单配置，body 和 queries 只会存在一个，需要保证一个不为空
        Body body = null;
        Query[] queries = null;
        // 根据表单类型，将请求参数转换成不同格式的数据
        if (methodInfo.getFormType() == FormType.BODY) {
            // RequestBody
            body = queryToRequestBodyConverter.convert(methodInfo, queryList);
        } else if (methodInfo.getFormType() == FormType.FORM_DATA) {
            // FormData
            body = queryToFormDataConverter.convert(methodInfo, queryList);
        } else {
            // 简单 Form，这时候 body 是 null
            queries = queryList.toArray(new Query[]{});
        }

        // 获取响应数据样例
        Response[] responses = responseAnalyzer.analyze(methodInfo);

        // 实际上，多个 url 可以指向同一个函数，因此会出现双重 for 循环
        // 常规代码，下面的循环体只会执行一次，1 个  url 对应于一个函数。
        for (String ctrlUrl : controllerInfo.getRequestPath()) {
            for (String methodUrl : methodInfo.getRequestPath()) {

                //解析 url
                Url url = this.getUrl(ctrlUrl, methodUrl);

                //解析 request
                Request request = new Request();
                request.setMethod(requestMethod);
                request.setDescription(requestDescription);
                request.setUrl(url);
                // RequestBody 配置
                request.setBody(body);
                // 查询参数配置
                url.setQuery(queries);

                Item item = new Item();
                item.setName(request.getDescription());
                item.setRequest(request);
                controllerApi.add(item);

                // 由于 Response 只能指定一个 Request，因此，后面的会覆盖前面的
                // 如果发生覆盖，有相同数据响应的，只有其中一个会有样例数据。
                if (responses != null) {
                    for (Response response : responses) {
                        response.setOriginalRequest(request);
                    }
                    item.setResponse(responses);
                }
            }
        }
    }

    /**
     * 获取每一个请求的访问路径
     * <p>
     * Concat controller-mapping and method-mapping, and return a longer url, which will start with "/".
     *
     * @param ctrl   controller url mapping
     * @param method method url mapping
     * @return raw
     * @see Url
     */
    private Url getUrl(String ctrl, String method) {
        Environment environment = this.postmanBuilder.getEnvironment();

        String subRaw = ctrl + method;
        String raw = environment.getBaseUrl() + subRaw;
        String[] path = subRaw.substring(1).split("/");

        Url url = new Url();
        url.setHost(environment.getHost());
        url.setProtocol(environment.getProtocol());
        url.setRaw(raw);
        url.setPath(path);
        return url;
    }

    // getter/setter ---------------------------------------------------------------------------------------------------------

    public QueryAnalyzer getQueryAnalyzer() {
        return queryAnalyzer;
    }

    public void setQueryAnalyzer(QueryAnalyzer queryAnalyzer) {
        this.queryAnalyzer = queryAnalyzer;
    }

    public QueryToFormDataConverter getQueryToFormDataConverter() {
        return queryToFormDataConverter;
    }

    public void setQueryToFormDataConverter(QueryToFormDataConverter queryToFormDataConverter) {
        this.queryToFormDataConverter = queryToFormDataConverter;
    }

    public QueryToRequestBodyConverter getQueryToRequestBodyConverter() {
        return queryToRequestBodyConverter;
    }

    public void setQueryToRequestBodyConverter(QueryToRequestBodyConverter queryToRequestBodyConverter) {
        this.queryToRequestBodyConverter = queryToRequestBodyConverter;
    }

    public ResponseAnalyzer getResponseAnalyzer() {
        return responseAnalyzer;
    }

    public void setResponseAnalyzer(ResponseAnalyzer responseAnalyzer) {
        this.responseAnalyzer = responseAnalyzer;
    }
}
